package ks.client.lobby;

import ks.client.UserContext;
import ks.client.controllers.ConnectController;
import ks.client.interfaces.ILobby;
import ks.client.interfaces.ILobbyInitialize;
import ks.client.ipc.Client;

/**
 * GUI-based controller to manage request from user to connect to the KombatGames
 * server with given user and password.
 * 
 * @author George Heineman
 */
public class ConnectButtonController {
	
	/** Frame being managed. */
	ConnectFrame frame;
	
	/** When constructing controller, need frame. */
	public ConnectButtonController (ConnectFrame frame) {
		this.frame = frame;
	}
	
	public ILobby process(ILobbyInitialize lobbyInit) {
		// initiate a new context
		UserContext context = new UserContext();
		context.setUser(frame.loginUserText.getText());

		// get hash for password.
		String password = frame.extractPassword(frame.loginPassText);
		password = Client.sha1(password);
		context.setPassword(password);
		
		context.setSelfRegister(false);
		
		// Create LobbyGUI presuming successful connection
		// for now it is visible (debugging purposes) but it
		// will become visible once secure connection has been
		// established.
		LobbyFrame lobby = new LobbyFrame (context);
		lobbyInit.initializeLobby(lobby);
		lobby.setVisible(true);
					
		// just when I said it was uncommon for controllers to invoke other
		// controllers, look what comes up naturally...
		if (new ConnectController(lobby).process(context)) {
			// success
		
			// within this anonymous class we can access
			// our outer class with this little bit of syntax. Make
			// sure to dispose for thread.
			frame.setVisible(false);
			frame.dispose();
		}	
		
		return lobby;
	}
}
